package com.zky.gulimall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zky.common.exception.NoStockException;
import com.zky.common.to.SkuHasStockVo;
import com.zky.common.to.mq.OrderTo;
import com.zky.common.to.mq.SecKillOrderTo;
import com.zky.common.utils.DateUtil;
import com.zky.common.utils.R;
import com.zky.common.vo.MemberRespVo;
import com.zky.gulimall.order.config.AlipayTemplate;
import com.zky.gulimall.order.constant.OrderConstant;
import com.zky.gulimall.order.entity.OrderItemEntity;
import com.zky.gulimall.order.entity.PaymentInfoEntity;
import com.zky.gulimall.order.enume.AliPayOrderPayedStatusEnum;
import com.zky.gulimall.order.enume.OrderStatusEnum;
import com.zky.gulimall.order.feign.CartFeignService;
import com.zky.gulimall.order.feign.MemberFeignService;
import com.zky.gulimall.order.feign.ProductFeignService;
import com.zky.gulimall.order.feign.WareFeignService;
import com.zky.gulimall.order.interceptor.UserLoginInterceptor;
import com.zky.gulimall.order.service.OrderItemService;
import com.zky.gulimall.order.service.PaymentInfoService;
import com.zky.gulimall.order.to.OrderCreateTo;
import com.zky.gulimall.order.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;

import com.zky.gulimall.order.dao.OrderDao;
import com.zky.gulimall.order.entity.OrderEntity;
import com.zky.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;


@Service("orderService")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private AlipayTemplate alipayTemplate;

    public static ThreadLocal<OrderSubmitVo> confirmVo = new ThreadLocal<OrderSubmitVo>();


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = UserLoginInterceptor.threadLocal.get();
        log.warn("主线程：" + Thread.currentThread().getName());
        //解决异步形势feign请求头丢失问题
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddr = CompletableFuture.runAsync(() -> {
            //远程查询会员收货地址
            //调用feign前请求头同步主线程请求信息
            RequestContextHolder.setRequestAttributes(attributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            log.warn("getAddress 线程：" + Thread.currentThread().getName());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> orderItem = CompletableFuture.runAsync(() -> {
            //远程查询购物车选中的购物项
            //调用feign前请求头同步主线程请求信息
            RequestContextHolder.setRequestAttributes(attributes);
            List<OrderItemVo> orderItemVos = cartFeignService.currentMemberCartItem();
            log.warn("currentMemberCartItem 线程：" + Thread.currentThread().getName());
            confirmVo.setItems(orderItemVos);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            if (!CollectionUtils.isEmpty(items)) {
                //批量去查询库存
                List<Long> skuIdList = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
                List<SkuHasStockVo> stock = wareFeignService.getSkuHasStock(skuIdList);
                if (!CollectionUtils.isEmpty(stock)) {
                    //转为map
                    Map<Long, Boolean> booleanMap = stock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                    confirmVo.setStocks(booleanMap);
                }
            }
        }, executor);

        CompletableFuture.allOf(getAddr, orderItem).get();

        //查询用户积分,从session获取，登陆session未过期区间，积分有变更会有一些问题，不过暂不考虑，知道这点就行
        confirmVo.setIntegration(memberRespVo.getIntegration());

        //其他数据自动计算

        //防止重复令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        confirmVo.setOrderToken(token);
        //防止重复过期时间设置为30分钟
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);


        return confirmVo;
    }

    // @GlobalTransactional
    @Override
    public OrderSubmitResponseVo submitOrder(OrderSubmitVo submitVo) {
        //初始化一下提交的数据，后续可以复用
        confirmVo.set(submitVo);
        //检验参数
        OrderSubmitResponseVo responseVo = new OrderSubmitResponseVo();
        MemberRespVo memberRespVo = UserLoginInterceptor.threadLocal.get();
        responseVo.setCode(0);
        boolean b = checkParam(submitVo);
        if (!b) {
            log.error("参数检验错误，submitVo：" + submitVo);
            throw new RuntimeException("参数检验错误");
        }
        //验证令牌[令牌的对比和删除需要保证原子性，加分布式锁],0令牌失败，1令牌成功
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                submitVo.getOrderToken());
        if (result == null || result == 0) {
            //验证不通过
            responseVo.setCode(1);
            //其他待处理
            return responseVo;
        }
        //创建订单
        OrderCreateTo order = createOrder();
        //验价
        BigDecimal payAmount = order.getOrder().getPayAmount();//服务端计算价格
        log.warn("服务端计算价格 payAmount:" + payAmount);
        BigDecimal payPrice = submitVo.getPayPrice();  //前端传过来价格(来自缓存)
        log.warn("前端传过来价格(来自缓存) payPrice:" + payPrice);

        //相差小于0.01就算成功，允许小数精度误差
        boolean compare = Math.abs(payAmount.subtract(payPrice).doubleValue()) >= 0.01;
        log.warn("价格比较结果 compare:" + compare);
        if (compare) {
            //比价失败
            //比价失败code
            responseVo.setCode(2);
            return responseVo;
        } else {
            //比价成功
            //保存订单
            saveOrder(order);
            //锁定库存,只要有异常就抛异常回滚
            WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
            wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
            List<OrderItemEntity> items = order.getItems();
            if (!CollectionUtils.isEmpty(items)) {
                List<OrderItemVo> itemVoList = items.stream().map(e -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(e.getSkuId());
                    orderItemVo.setCount(e.getSkuQuantity());
                    orderItemVo.setTitle(e.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(itemVoList);
            }
            R stock = wareFeignService.orderLockStock(wareSkuLockVo);
            log.warn("submitOrder orderLockStock ,result：" + stock.isSuccess());
            if (stock.isSuccess()) {
                //锁定成功
                String data = JSON.toJSONString(stock.get("data"));
                Boolean hasStock = JSON.parseObject(data, new TypeReference<Boolean>() {
                });
                log.warn("hasStock:" + hasStock);
                responseVo.setOrder(order.getOrder());

                try {
                    //发送MQ,指定时间后关闭订单
                    //补偿机制方案
                    //1 建立数据库消息表，定期扫描有异常的消息，重试补偿
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                } catch (AmqpException e) {
                    e.printStackTrace();
                }
            } else {
                //锁定失败
                //3代表库存锁定失败
                String msg = stock.getMsg();
                throw new NoStockException(msg);
            }

        }
        return responseVo;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询当前订单最新状态
        OrderEntity byId = this.getById(orderEntity.getId());
        //只有待付款才关单,有订单状态，能防止消息重复投递
        if (byId != null && byId.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            //关单
            OrderEntity entity = new OrderEntity();
            entity.setId(byId.getId());
            entity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(entity);
            //给库存队列发送消息，库存解锁
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
    }

    @Override
    public PayVo getPayOrder(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        if (orderEntity == null) {
            return null;
        }
        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderEntity.getOrderSn()));
        payVo.setTotal_amount(orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());
        payVo.setOut_trade_no(orderEntity.getOrderSn());
        payVo.setSubject(list.get(0).getSkuName());
        payVo.setBody(list.get(0).getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = UserLoginInterceptor.threadLocal.get();
        log.warn("memberRespVo:{}", memberRespVo);
        log.warn("queryPageWithItem，当前线程name:{},当前线程id:{}", Thread.currentThread().getName(), Thread.currentThread().getId());


        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return null;
        }
        List<OrderEntity> entityList = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(entityList);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        //保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(asyncVo.getTrade_no());
        infoEntity.setOrderSn(asyncVo.getOut_trade_no());
        infoEntity.setPaymentStatus(asyncVo.getTrade_status());
        infoEntity.setCreateTime(DateUtil.getDate(asyncVo.getGmt_create()));
        infoEntity.setCallbackTime(DateUtil.getDate(asyncVo.getNotify_time()));
        infoEntity.setSubject(asyncVo.getSubject());
        infoEntity.setTotalAmount(new BigDecimal(asyncVo.getTotal_amount()));
        paymentInfoService.save(infoEntity);

        //修改订单状态
        if (asyncVo.getTrade_status().equals(AliPayOrderPayedStatusEnum.TRADE_SUCCESS.getCode()) ||
                asyncVo.getTrade_status().equals(AliPayOrderPayedStatusEnum.TRADE_FINISHED.getCode())) {
            baseMapper.updateOrderStatus(asyncVo.getOut_trade_no(), OrderStatusEnum.PAYED.getCode());
        }

        return "success";
    }

    @Override
    public Boolean checkSign(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");//实际测试注释掉才能成功，否则失败
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名
        if (signVerified) {
            log.warn("checkSign rsaCheckV1 success");
        } else {
            log.error("checkSign rsaCheckV1 fail");
        }
        return signVerified;
    }

    @Override
    public void createSecKillOrder(SecKillOrderTo secKillOrderTo) {
        // 保存订单信息
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(secKillOrderTo.getOrderSn());
        entity.setMemberId(secKillOrderTo.getMemberId());
        entity.setCreateTime(new Date());
        entity.setModifyTime(new Date());
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal decimal = secKillOrderTo.getSeckillPrice().multiply(new BigDecimal(secKillOrderTo.getNum()));
        entity.setPayAmount(decimal);
        this.save(entity);
        //保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(secKillOrderTo.getOrderSn());
        itemEntity.setRealAmount(decimal);
        //todo 获取sku详细信息
        itemEntity.setSkuQuantity(secKillOrderTo.getNum());
        orderItemService.save(itemEntity);
    }

    private boolean checkParam(OrderSubmitVo submitVo) {
        if (submitVo.getAddrId() == null) {
            return false;
        }
        if (StringUtils.isEmpty(submitVo.getOrderToken())) {
            return false;
        }
        if (StringUtils.isEmpty(submitVo.getNote())) {
            return false;
        }
        if (submitVo.getPayType() == null) {
            return false;
        }
        if (submitVo.getPayPrice() == null) {
            return false;
        }
        return true;
    }


    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        //1 生成订单号(mybatisplus IdWorker生成订单Id在集群模式会不会重复，待核实验证)
        String orderSn = IdWorker.getTimeId();
        OrderEntity entity = getOrderEntity(orderSn);
        createTo.setOrder(entity);
        //获取当前用户购物车购物项，构建订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        createTo.setItems(orderItemEntities);
        //价格，积分信息
        computePrice(entity, orderItemEntities);

        return createTo;
    }

    private OrderEntity getOrderEntity(String orderSn) {
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        //设置会员id
        MemberRespVo memberRespVo = UserLoginInterceptor.threadLocal.get();
        entity.setMemberId(memberRespVo.getId());
        //2 获取收货地址信息
        R fare = wareFeignService.getFare(confirmVo.get().getAddrId());
        if (fare.isSuccess()) {
            String data = JSON.toJSONString(fare.get("data"));
            FareVo fareVo = JSON.parseObject(data, new TypeReference<FareVo>() {
            });
            log.warn("fareVo:" + fareVo);
            //设置运费
            entity.setFreightAmount(fareVo.getFare());
            entity.setReceiverName(fareVo.getAddress().getName());
            //收货人城市
            entity.setReceiverCity(fareVo.getAddress().getCity());
            //收货人详细地址
            entity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
            //收货人手机号
            entity.setReceiverPhone(fareVo.getAddress().getPhone());
            //邮编
            entity.setReceiverPostCode(fareVo.getAddress().getPostCode());
            //省份
            entity.setReceiverProvince(fareVo.getAddress().getProvince());
            //区域
            entity.setReceiverRegion(fareVo.getAddress().getRegion());

            //设置订单状态未待付款
            entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
            //订单自动确认时间，默认设置7天
            entity.setAutoConfirmDay(7);

        }
        return entity;
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定购物项价格
        List<OrderItemVo> orderItemVos = cartFeignService.currentMemberCartItem();
        log.warn("buildOrderItems orderItemVos:" + orderItemVos);
        List<OrderItemEntity> itemEntities = null;
        if (!CollectionUtils.isEmpty(orderItemVos)) {
            itemEntities = orderItemVos.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                //订单信息：订单号
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return itemEntities;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity entity = new OrderItemEntity();
        //商品spu信息
        Long skuId = cartItem.getSkuId();
        R infoBySkuId = productFeignService.spuInfoBySkuId(skuId);
        if (infoBySkuId.isSuccess()) {
            String data = JSON.toJSONString(infoBySkuId.get("data"));
            SpuInfoVo spuInfoVo = JSON.parseObject(data, new TypeReference<SpuInfoVo>() {
            });
            if (spuInfoVo != null) {
                entity.setSpuId(spuInfoVo.getId());
                entity.setSpuBrand(String.valueOf(spuInfoVo.getBrandId()));
                entity.setSpuName(spuInfoVo.getSpuName());
                entity.setCategoryId(spuInfoVo.getCatalogId());
            }
        }
        //商品sku信息
        entity.setSkuId(cartItem.getSkuId());
        entity.setSkuName(cartItem.getTitle());
        entity.setSkuPic(cartItem.getImage());
        entity.setSkuPrice(cartItem.getPrice());
        List<String> skuAttrs = cartItem.getSkuAttrs();
        if (!CollectionUtils.isEmpty(skuAttrs)) {
            String delimitedString = StringUtils.collectionToDelimitedString(skuAttrs, ";");
            entity.setSkuAttrsVals(delimitedString);
        }
        entity.setSkuQuantity(cartItem.getCount());
        //优惠信息，暂不做
        //积分信息
        int giftIntegration = cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue();
        entity.setGiftGrowth(giftIntegration);
        entity.setGiftIntegration(giftIntegration);

        //订单项价格信息
        //减去优惠实际价格
        entity.setPromotionAmount(new BigDecimal(0));
        entity.setCouponAmount(new BigDecimal(0));
        entity.setIntegrationAmount(new BigDecimal(0));
        //当前订单项实际总金额
        BigDecimal total = entity.getSkuPrice().multiply(new BigDecimal(String.valueOf(entity.getSkuQuantity())));
        //扣除优惠后价格
        BigDecimal real = total.subtract(entity.getPromotionAmount()).subtract(entity.getCouponAmount()).subtract(entity.getIntegrationAmount());
        entity.setRealAmount(real);
        return entity;
    }

    private void computePrice(OrderEntity entity, List<OrderItemEntity> orderItemEntities) {
        //订单总额,叠加订单项
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal giftIntegration = new BigDecimal("0.0");
        BigDecimal giftGrowth = new BigDecimal("0.0");
        if (!CollectionUtils.isEmpty(orderItemEntities)) {
            for (OrderItemEntity itemEntity : orderItemEntities) {
                //每一项总价
                total = total.add(itemEntity.getRealAmount());
                promotion = promotion.add(itemEntity.getPromotionAmount());
                coupon = coupon.add(itemEntity.getCouponAmount());
                integration = integration.add(itemEntity.getIntegrationAmount());
                giftIntegration = giftIntegration.add(new BigDecimal(itemEntity.getGiftIntegration()));
                giftGrowth = giftGrowth.add(new BigDecimal(itemEntity.getGiftGrowth()));
            }
        }
        entity.setTotalAmount(total);
        //应付价格还要加上运费
        entity.setPayAmount(total.add(entity.getFreightAmount()));
        entity.setPromotionAmount(promotion);
        entity.setCouponAmount(coupon);
        entity.setIntegrationAmount(integration);

        //设置积分等信息
        entity.setIntegration(giftIntegration.intValue());
        entity.setGrowth(giftGrowth.intValue());
        //0 未删除
        entity.setDeleteStatus(0);
    }


    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        //保存订单信息
        OrderEntity orderOrder = order.getOrder();
        orderOrder.setModifyTime(new Date());
        orderOrder.setCreateTime(new Date());
        baseMapper.insert(orderOrder);
        //保存订单项数据
        orderItemService.saveBatch(order.getItems());
    }
}